"use server";

import {NextResponse} from "next/server";
import {setRefreshToken, setToken} from "@/lib/auth";

const FASTAPI_LOGIN_URL = "http://localhost:8000/auth/token_v2";

export async function POST(request) {
    // 获取/login发来的请求数据
    const requestData = await request.json();
    // 会在终端打印，不在浏览器客户端打印
    // console.log(requestData);
    // 转换json格式
    const jsonData = JSON.stringify(requestData);
    // console.log(jsonData);
    // 构建请求信息：请求方式、请求头、请求体
    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: jsonData,
    }
    // 向fastapi请求数据
    const response = await fetch(FASTAPI_LOGIN_URL, requestOptions);
    const responseData = await response.json();
    // console.log(responseData);
    if (response.ok) {
        // console.log("logged in");
        const {access_token, refresh_token} = responseData;
        await setToken(access_token);
        await setRefreshToken(refresh_token);
        return NextResponse.json({"loggedIn": true}, {status: 200});
    }
    // 登录失败返回响应信息
    return NextResponse.json({"loggedIn": false, ...responseData}, {status: 400});
}